﻿using IDEAMS.core;
using IDEAMS.utils;
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace IDEAMS.model.alarm
{
    public class AlarmInfoCollection : SHCollection<AlarmInfo>
    {
        private static ILog logger = LogManager.GetLogger(typeof(AlarmInfoCollection));

        public AlarmInfoCollection() { }

        public AlarmInfoCollection(AlarmInfoCollection collection)
        {
            collection.ForEach(x =>
            {
                AlarmInfo data = new AlarmInfo(x);
                dataList.Add(data);
                return false;
            });
        }

        public override bool Equals(AlarmInfo obj, object key)
        {
            return (string)key == obj.key;
        }

        public override void CopyTo(AlarmInfo src, AlarmInfo dst)
        {
            dst.Copy(src);
        }

        public AlarmInfoCollection Clone()
        {
            return new AlarmInfoCollection(this);
        }

        public bool Save(string serialNo)
        {
            bool rn = true;
            rwLock.EnterReadLock();
            try
            {
                string dataFile = string.Format(TW_App.fileManager.alarmInfoCollectionFile, serialNo);
                rn = XmlUtil.Save<AlarmInfoCollection>(dataFile, this);
            }
            finally
            {
                rwLock.ExitReadLock();
            }
            return rn;
        }

        public int Load(string serialNo)
        {
            int rn = -1;
            rwLock.EnterWriteLock();
            try
            {
                string dataFile = string.Format(TW_App.fileManager.alarmInfoCollectionFile, serialNo);
                bool existsFlag = File.Exists(dataFile);
                if(!existsFlag)
                {
                    return -2;
                }

                AlarmInfoCollection collection = XmlUtil.Load<AlarmInfoCollection>(dataFile);
                if(collection != null)
                {
                    dataList.Clear();
                    collection.ForEach(x =>
                    {
                        AlarmInfo data = x.Clone();
                        dataList.Add(data);
                        return false;
                    });
                    rn = 0;
                }
            }
            finally
            {
                rwLock.ExitWriteLock();
            }
            return rn;
        }
    }
}
